package com.xmy.erp.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.erp.entity.Admin;
import com.xmy.erp.entity.Organization;
import com.xmy.erp.service.IAdminService;
import com.xmy.erp.service.IAppointSchoolService;
import com.xmy.erp.service.IOrganizationService;
import com.xmy.study.respons.ProfileResult;
import com.xmy.study.shiro.realm.XmyStudyRealm;
import org.apache.shiro.authc.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.List;

public class AdminRealm extends XmyStudyRealm {

    @Autowired
    @Lazy
    IAdminService iAdminService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IAppointSchoolService iAppointSchoolService;

    /**
     * 认证方法
     *  参数：传递的用户名密码
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登录的用户名密码（token）
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = new String( upToken.getPassword());

        //System.out.print("username:"+username);
        //System.out.print("password:"+password);

        //2.根据用户名查询数据库
        QueryWrapper<Admin> queryWrapper =  new QueryWrapper<>();

        queryWrapper.eq("account",username);
        queryWrapper.eq("pwd",password);

        ProfileResult profileResult = new ProfileResult();

        Admin admin = iAdminService.getOne(queryWrapper);
        //3.判断用户是否存在或者密码是否一致
        if(admin != null) {
            BeanUtils.copyProperties(admin,profileResult);
            //管辖校区
            List<Long> appointIdList = new ArrayList<>();
            if(admin.getIsSuper() == 1 || admin.getGovernMode()==1){
                QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
                organizationQueryWrapper.eq("type",1);
                appointIdList = iOrganizationService.getOrganiztionId(organizationQueryWrapper);
            }else {
                appointIdList =  iAppointSchoolService.getSchoolIdListForForId(admin.getId(),2);
            }
            profileResult.setSchoolIdList(appointIdList);
            //4.如果一致返回安全数据
            //构造方法：安全数据，密码，realm域名
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(profileResult,admin.getPwd(),this.getName());
            return info;
        }
        //5.不一致，返回null（抛出异常）
        return null;
    }
}
